<template>
  <div class="material-requisition-wrap">
    <!-- 查询条件区域 -->
    <el-card class="search-card mb16">
      <el-form :model="searchForm" inline label-width="80px">
        <el-form-item label="原材料">
          <el-select
              v-model="searchForm.materialId"
              placeholder="请选择原材料"
              clearable
              style="width: 200px"
          >
            <el-option
                v-for="m in materialList"
                :key="m.materialId"
                :label="'ID:'+m.materialId+' (库存'+m.num+')'"
                :value="m.materialId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="员工">
          <el-select
              v-model="searchForm.employeeId"
              placeholder="请选择员工"
              clearable
              style="width: 200px"
          >
            <el-option v-for="e in empOpts" :key="e.value" :label="e.label" :value="e.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库">
          <el-select
              v-model="searchForm.warehouseId"
              placeholder="请选择仓库"
              clearable
              style="width: 200px"
          >
            <el-option v-for="w in warehouseOpts" :key="w.value" :label="w.label" :value="w.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
          >
            <el-option :value="null" label="全部" />
            <el-option :value="0" label="未审核" />
            <el-option :value="1" label="已审核" />
            <el-option :value="2" label="已领取" />
            <el-option :value="3" label="已领完" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作和分页区域 -->
    <el-row justify="space-between" align="middle" class="mb16">
      <el-button type="primary" :icon="Plus" @click="openAdd">新增领料</el-button>
      <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="size"
          v-model:current-page="page"
          @current-change="loadData"
      />
    </el-row>

    <!-- 表格数据区域 -->
    <el-card>
      <el-table
          :data="tableData"
          stripe
          v-loading="loading"
          :row-class-name="tableRowClassName"
          highlight-current-row
      >
        <el-table-column prop="requisitionId" label="ID" width="100" />
        <el-table-column prop="num" label="数量" width="120" />
        <el-table-column prop="unitId" label="单位" width="80">
          <template #default="{ row }">
            {{ unitOpts.find(i => i.value === row.unitId)?.label }}
          </template>
        </el-table-column>
        <el-table-column prop="materialId" label="原材料" width="150" />
        <el-table-column prop="employeeId" label="员工" width="150">
          <template #default="{ row }">
            {{ empOpts.find(i => i.value === row.employeeId)?.label }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouseId" label="仓库" width="150">
          <template #default="{ row }">
            {{ warehouseOpts.find(i => i.value === row.warehouseId)?.label }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="120">
          <template #default="{ row }">
            <el-tag :type="statusColor(row.status)" effect="dark">
              {{ statusMap[row.status] }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作列（含新增三颗状态按钮） -->
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="openEdit(row)">编辑</el-button>
            <el-popconfirm
                title="确定删除?"
                @confirm="handleDelete(row.requisitionId)"
                confirm-button-text="确认"
                cancel-button-text="取消">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>

            <!-- 审核 / 领取 / 领完 -->
            <el-button
                v-if="row.status === 0"
                size="small"
                type="success"
                @click="changeStatus(row,1)">
              审核
            </el-button>
            <el-button
                v-if="row.status === 1"
                size="small"
                type="warning"
                @click="changeStatus(row,2)">
              领取
            </el-button>
            <el-button
                v-if="row.status === 2"
                size="small"
                type="info"
                @click="changeStatus(row,3)">
              领完
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑抽屉 -->
    <el-drawer
        v-model="drawer"
        :title="isAdd ? '新增领料' : '编辑领料'"
        direction="rtl"
        size="420"
        destroy-on-close
        @closed="resetForm">
      <el-form ref="formRef" :model="form" label-width="90px">
        <el-form-item label="原材料" prop="materialId">
          <el-select
              v-model="form.materialId"
              placeholder="请选择原材料"
              clearable
              @change="onMaterialChange">
            <el-option
                v-for="m in materialList"
                :key="m.materialId"
                :label="'ID:'+m.materialId+' (库存'+m.num+')'"
                :value="m.materialId" />
          </el-select>
        </el-form-item>

        <!-- 以下只读，自动带出 -->
        <el-form-item label="单位">
          <el-input :modelValue="unitOpts.find(i=>i.value===form.unitId)?.label ?? ''" readonly />
        </el-form-item>
        <el-form-item label="仓库">
          <el-input :modelValue="warehouseOpts.find(i=>i.value===form.warehouseId)?.label ?? ''" readonly />
        </el-form-item>
        <el-form-item label="领料数量" prop="num">
          <el-input-number v-model="form.num" :min="0" :precision="2" style="width:100%" />
        </el-form-item>
        <el-form-item label="员工" prop="employeeId">
          <el-select v-model="form.employeeId" placeholder="请选择">
            <el-option v-for="e in empOpts" :key="e.value" :label="e.label" :value="e.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">未审核</el-radio>
            <el-radio :label="1">已审核</el-radio>
            <el-radio :label="2">已领取</el-radio>
            <el-radio :label="3">已领完</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawer=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  findAllRequisition as findAll,
  addRequisition as add,
  updateRequisition as update,
  deleteRequisition as deleteById,
  getUnitOpts,
  getEmpOpts,
  getWarehouseOpts,
  getMaterialMini
} from '../../api/wms.js'

const defaultForm = () => ({
  num: 0,
  unitId: 666,
  materialId: '',
  employeeId: '',
  warehouseId: 10,
  status: 0,
  procureId: 666,
  productId: 666,
  supplierId: 666,
  price: 666,
  totalPrice: 666
})

export default {
  name: 'MaterialRequisition',
  setup() {
    return { Plus }
  },
  data() {
    return {
      loading: false,
      tableData: [],
      total: 0,
      page: 1,
      size: 6,
      drawer: false,
      isAdd: true,
      form: defaultForm(),
      unitOpts: [],
      empOpts: [],
      warehouseOpts: [],
      statusMap: { 0: '未审核', 1: '已审核', 2: '已领取', 3: '已领完' },
      materialList: [],
      curMaterial: null,
      searchForm: {
        materialId: null,
        employeeId: null,
        warehouseId: null,
        status: null
      }
    }
  },
  mounted() {
    this.loadMaterialMini()
    this.loadSelect()
    this.loadData()
  },
  methods: {
    async loadSelect() {
      const [u, e, w] = await Promise.all([
        getUnitOpts(),
        getEmpOpts(),
        getWarehouseOpts()
      ])
      this.unitOpts = u
      this.empOpts = e
      this.warehouseOpts = w
    },
    async loadData() {
      this.loading = true
      try {
        const res = await findAll()
        let list = (res?.data?.data || res?.data || [])

        if (this.searchForm.materialId) {
          list = list.filter(item => item.materialId === this.searchForm.materialId)
        }
        if (this.searchForm.employeeId) {
          list = list.filter(item => item.employeeId === this.searchForm.employeeId)
        }
        if (this.searchForm.warehouseId) {
          list = list.filter(item => item.warehouseId === this.searchForm.warehouseId)
        }
        if (this.searchForm.status !== null && this.searchForm.status !== undefined) {
          list = list.filter(item => item.status === this.searchForm.status)
        }

        this.total = list.length
        this.tableData = list.slice((this.page - 1) * this.size, this.page * this.size)
      } finally {
        this.loading = false
      }
    },
    tableRowClassName({ row }) {
      if (row.status === 0) return 'warning-row'
      if (row.status === 3) return 'success-row'
      return ''
    },
    statusColor(st) {
      return ['warning', 'primary', 'info', 'success'][st] || 'info'
    },
    openAdd() {
      this.isAdd = true
      this.drawer = true
    },
    openEdit(row) {
      this.isAdd = false
      this.form = { ...row }
      this.drawer = true
    },
    async handleDelete(id) {
      await deleteById(id)
      ElMessage.success('删除成功')
      this.loadData()
    },
    async submit() {
      if (this.form.num > (this.curMaterial?.num || 0)) {
        ElMessage.error('领取数量超出库存，领取失败')
        return
      }
      const api = this.isAdd ? add : update
      await api(this.form)
      ElMessage.success(this.isAdd ? '新增成功' : '修改成功')
      this.drawer = false
      this.loadData()
    },
    resetForm() {
      this.form = defaultForm()
    },
    async loadMaterialMini() {
      this.materialList = await getMaterialMini()
    },
    onMaterialChange(val) {
      this.curMaterial = this.materialList.find(m => m.materialId === val) || null
      if (this.curMaterial) {
        this.form.unitId = this.curMaterial.unitId
        this.form.warehouseId = this.curMaterial.warehouseId
        this.form.num = this.curMaterial.num
      } else {
        this.form.unitId = 1
        this.form.warehouseId = 10
        this.form.num = 0
      }
    },
    handleSearch() {
      this.page = 1
      this.loadData()
    },
    resetSearch() {
      this.searchForm = {
        materialId: null,
        employeeId: null,
        warehouseId: null,
        status: null
      }
      this.page = 1
      this.loadData()
    },
    /* 新增：状态流转按钮统一入口 */
    async changeStatus(row, nextStatus) {
      try {
        await update({ ...row, status: nextStatus })
        ElMessage.success('操作成功')
        this.loadData()
      } catch {
        ElMessage.error('操作失败')
      }
    }
  }
}
</script>

<style scoped>
.material-requisition-wrap {
  padding: 20px;
  min-height: 100%;
}
.mb16 {
  margin-bottom: 16px;
}
.search-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}
::v-deep .el-form-item {
  margin-right: 16px;
  margin-bottom: 16px;
}
::v-deep .el-table .warning-row {
  --el-table-tr-bg-color: #fff8e6;
}
::v-deep .el-table .success-row {
  --el-table-tr-bg-color: #f0f9eb;
}
::v-deep .el-tag {
  margin-right: 0;
}
::v-deep .el-card__body {
  padding: 16px;
}
</style>